package com.invengo.base.utils;

import android.annotation.SuppressLint;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Stream;

import java8.util.stream.StreamSupport;
import me.jessyan.autosize.utils.LogUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class RequestBodyUtils {
    private static Gson gson = new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation()
            .create();

    public static RequestBody parseWithAnd(Map<String, Object> params) {
        return RequestBody.create(MediaType.parse("application/x-www-form-urlencoded; charset=UTF-8"), parseJson(params, true));
    }

    public static RequestBody parse(Map<String, Object> params) {

        return RequestBody.create(MediaType.parse("application/json-patch+json; charset=UTF-8"), parseJson(params, false));
    }

    public static <T> RequestBody parse(ParseData parseData, T t) {
        Map<String, Object> params = parseData.handler(t);
        return RequestBody.create(MediaType.parse("application/json-patch+json; charset=UTF-8"), parseJson(params, false));
    }

    @FunctionalInterface
    public interface ParseData<T> {
        Map<String, Object> handler(T t);
    }

    public static RequestBody assembleOffline(String json, boolean isForm) {
        return RequestBody.create(MediaType.parse(isForm ? "application/x-www-form-urlencoded; charset=UTF-8" : "application/json-patch+json; charset=UTF-8"), json);
    }


    public static String parseJson(Map<String, Object> params, boolean needAnd) {
        if (!needAnd)
            return gson.toJson(params);
        StringBuffer sp = new StringBuffer();
        for (String s : params.keySet()) {
            if (sp.length() > 0) {
                sp.append("&");
            }
            sp.append(s + "=");
            sp.append(gson.toJson(params.get(s)));
        }
        return sp.toString();
    }

    public static String parseJson(List<Object> params) {
        return gson.toJson(params);
    }
}
